import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../model/cart_info.dart';

class CartProvider with ChangeNotifier {
  String cartString = "[]";
  List<CartInfoMode> cartList = [];
  double _allPrice = 0.0; // 总价
  int _allGoodsCount = 0; // 商品个数
  bool _isAllCheck = true; // 是否全选
  int get allGoodsCount => _allGoodsCount;
  double get allPrice => _allPrice;
  bool get isAllCheck => _isAllCheck;

  save(goodsId, goodsName, count, price, images) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo') ?? '[]';
    var temp = cartString == null ? [] : json.decode(cartString.toString());
    List<Map> tempList = (temp as List).cast();
    var isHave = false; // 默认没有该商品
    int ival = 0; // 循环的索引
    tempList.forEach((item) {
      // 找到已加入购物车商品
      if (item['goodsId'] == goodsId) {
        tempList[ival]['count'] = item['count'] + 1;
        cartList[ival].count++;
        isHave = true;
      }
      ival++;
    });
    if (!isHave) {
      Map<String, dynamic> newGoods = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images,
        'isCheck': true, // 是否已选择
      };
      tempList.add(newGoods);
      cartList.add(new CartInfoMode.fromJson(newGoods));
    }
    cartString = json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString); // 持久化
    await getCartInfo();
    notifyListeners();
  }

  remove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('cartInfo');
    notifyListeners();
  }

  getCartInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    cartList = [];
    if (cartString == null) {
      cartList = [];
    } else {
      List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
      _allPrice = 0;
      _allGoodsCount = 0;
      _isAllCheck = true; // 默认全选

      tempList.forEach((item) {
        if (item['isCheck']) {
          _allPrice += (item['count'] * item['price']);
          _allGoodsCount += item['count'];
        } else {
          // 有一个商品没有勾选，全选=false
          _isAllCheck = false;
        }
        cartList.add(new CartInfoMode.fromJson(item));
      });
    }
    notifyListeners();
  }

  /// 购物车勾选商品
  changeCheckState(CartInfoMode cartItem) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString) as List).cast();
    for (var i = 0; i < tempList.length; i++) {
      if (tempList[i]['goodsId'] == cartItem.goodsId) {
        tempList[i] = cartItem.toJson(); // 把对象变成Map值
      }
    }
    cartString = json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);
    await getCartInfo(); // 重新读取购物车数据
  }

  /// 全选按钮
  void changeAllCheckBtnState(bool isCheck) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
    List<Map> newList = []; // 用于组成新的持久化数据
    for (var item in tempList) {
      var newItem = item; // 复制性的变量，Dart不让循环时修改原值
      newItem['isCheck'] = isCheck;
      newList.add(newItem);
    }
    cartString = json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);
    await getCartInfo(); // 重新读取购物车数据
  }

  /// 购物车商品数据量加减
  void addOrReduceAction(cartItem, String type) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    if (type == 'add') {
      cartItem.count++;
      print(cartItem.count);
    } else if (cartItem.count > 1) {
      cartItem.count--;
    }
    for (var i = 0; i < tempList.length; i++) {
      if (tempList[i]['goodsId'] == cartItem.goodsId) {
        tempList[i] = cartItem.toJson(); // 把对象变成Map值
      }
    }
    cartString = json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);
    await getCartInfo();
  }

  void deleteOneGoods(String goodsId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    int deleteIndex = 0;
    for (var i = 0; i < tempList.length; i++) {
      if (tempList[i]['goodsId'] == goodsId) {
        deleteIndex = i;
      }
    }
    tempList.removeAt(deleteIndex);
    cartString = json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);
    await getCartInfo();
  }
}
